package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.api.CommonResult;
import org.example.model.Store;
import org.example.service.StoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "StoreController", description = "门店信息")
@Controller
@RequestMapping(value = "store")
public class StoreController {
    private static final Logger LOGGER = LoggerFactory.getLogger(StoreController.class);

    @Autowired
    private StoreService storeService;

    @ApiOperation("获取所有门店信息")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<Store>> listAll() {
        return CommonResult.success(storeService.getStoreList());
    }

    @ApiOperation("添加门店信息")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody Store store) {
        CommonResult commonResult;
        int count = storeService.create(store);
        if (count == 1) {
            commonResult = CommonResult.success(store);
            LOGGER.debug("createStore success:{}", store);
        } else {
            commonResult = CommonResult.failed("");
            LOGGER.debug("createStore success:{}", store);
        }
        return commonResult;
    }

    @ApiOperation("删除门店信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public CommonResult delete(@PathVariable("id") Long id) {
        CommonResult commonResult;
        int count = storeService.delete(id);
        if (count == 1) {
            LOGGER.debug("deleteStore success : id={}", id);
            return CommonResult.success(null);
        } else {
            LOGGER.debug("deleteStore fail", id);
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("更新门店信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@PathVariable("id") Long id, @RequestBody Store store) {
        CommonResult commonResult;
        int count = storeService.update(id, store);
        if (count == 1) {
            commonResult = CommonResult.success(store);
            LOGGER.debug("updateStore success: {}", store);
        } else {
            commonResult = CommonResult.failed("更新失败");
            LOGGER.debug("updateStore failed: {}", store);
        }
        return commonResult;
    }

    @ApiOperation("根据id查询门店信息")
    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getById(@PathVariable("id") Long id) {
        return CommonResult.success(storeService.getStoreById(id));
    }
}
